import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_comment.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "forgetSetPasswordPage")
class ForgetSetPswPage extends StatefulWidget {
  final int type;
  final String code;
  ForgetSetPswPage({this.type = 0, required this.code});
  @override
  ForgetSetPswPageState createState() => ForgetSetPswPageState();
}

class ForgetSetPswPageState extends State<ForgetSetPswPage> {
  String phone = '';
  // String areaCode = '86';
  final _formKey = GlobalKey<FormState>();
  FocusNode pwsFocusNode = FocusNode();
  TextEditingController pwsController = TextEditingController();
  FocusNode againFocusNode = FocusNode();
  bool _canNext = false;
  TextEditingController againController = TextEditingController();
  bool pwsobscureText = true;
  bool againobscureText = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          S.of(context).Forgot_password,
        ),
      ),
      body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: ClickUtils.debounce(() {
            // 触摸收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          }),
          child: Container(
              padding: EdgeInsets.only(left: 30.w, top: 30.w, right: 30.w),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text(
                          S().login_Reset_password,
                          style: FontStyles.headerTextStyle_20,
                        )
                      ],
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    // Row(
                    //   children: [
                    Text(
                        (widget.type == 1
                                ? S().login_mobile_email
                                : S().login_mobile_number) +
                            ':' +
                            '$phone',
                        // (areaCode.isNotEmpty ? '+' : '') +
                        // '$areaCode $phone',
                        style: FontStyles.headerTextStyle_16),
                    // ],
                    // ),
                    SizedBox(
                      height: 24,
                    ),
                    TextField(
                      enableInteractiveSelection: false,
                      focusNode: pwsFocusNode,
                      controller: pwsController,
                      inputFormatters: [
                        FilteringTextInputFormatter.deny(appContext.emojiRegexp)
                      ],
                      onChanged: (value) {
                        if (!UtilsComment.checkPasswordFormal(value)) {
                          if (_canNext == false &&
                              mounted &&
                              value == againController.text) {
                            setState(() {
                              _canNext = true;
                            });
                          }
                        } else {
                          if (_canNext == true && mounted) {
                            setState(() {
                              _canNext = false;
                            });
                          }
                        }
                      },
                      onSubmitted: (value) {
                        // print(value);
                        // pwsFocusNode.unfocus();
                        againFocusNode.requestFocus();
                      },
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.black.withOpacity(0.4),
                      ),
                      cursorColor: ThemeColor.primaryColor,
                      obscureText: pwsobscureText,
                      keyboardType: TextInputType.visiblePassword,
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.symmetric(vertical: 0),
                          suffixIcon: GestureDetector(
                            onTap: ClickUtils.debounce(() {
                              if (mounted) {
                                setState(() {
                                  pwsobscureText = !pwsobscureText;
                                });
                              }
                            }),
                            child: Container(
                              width: 20,
                              alignment: Alignment.centerRight,
                              child: Image.asset(
                                pwsobscureText
                                    ? 'assets/images/comment_obscureText_open.png'
                                    : 'assets/images/comment_obscureText_close.png',
                                width: 20,
                                // color: Colors.red,
                                height: pwsobscureText ? 20 : 14,
                              ),
                            ),
                          ),
                          border:
                              OutlineInputBorder(borderSide: BorderSide.none),
                          hintText: S.current.logon_enterpsw,
                          hintStyle: TextStyle(
                              fontSize: 16,
                              color: Colors.black.withOpacity(0.4))),
                    ),
                    Container(
                      color: Colors.black.withOpacity(0.2),
                      height: 0.5,
                      margin: EdgeInsets.only(bottom: 24),
                    ),
                    TextField(
                      enableInteractiveSelection: false,
                      inputFormatters: [
                        FilteringTextInputFormatter.deny(appContext.emojiRegexp)
                      ],
                      focusNode: againFocusNode,
                      controller: againController,
                      onSubmitted: (value) {
                        print(value);
                      },
                      onChanged: (value) {
                        if (value == pwsController.text &&
                            UtilsComment.checkPasswordFormal(value)) {
                          if (_canNext == false && mounted) {
                            setState(() {
                              _canNext = true;
                            });
                          }
                        } else {
                          if (_canNext == true && mounted) {
                            setState(() {
                              _canNext = false;
                            });
                          }
                        }
                      },
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.black.withOpacity(0.4),
                      ),
                      cursorColor: ThemeColor.primaryColor,
                      obscureText: againobscureText,
                      keyboardType: TextInputType.visiblePassword,
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.symmetric(vertical: 0),
                          suffixIcon: GestureDetector(
                            onTap: ClickUtils.debounce(() {
                              if (mounted) {
                                setState(() {
                                  againobscureText = !againobscureText;
                                });
                              }
                            }),
                            child: Container(
                              // color: Colors.red,
                              width: 20,
                              alignment: Alignment.centerRight,
                              child: Image.asset(
                                againobscureText
                                    ? 'assets/images/comment_obscureText_open.png'
                                    : 'assets/images/comment_obscureText_close.png',
                                width: 20,
                                // color: Colors.red,
                                height: againobscureText ? 20 : 14,
                              ),
                            ),
                          ),
                          border:
                              OutlineInputBorder(borderSide: BorderSide.none),
                          hintText: S.current.logon_enteragain,
                          hintStyle: TextStyle(
                              fontSize: 16,
                              color: Colors.black.withOpacity(0.4))),
                    ),
                    Container(
                      color: Colors.black.withOpacity(0.2),
                      height: 0.5,
                    ),
                    GestureDetector(
                        child: Container(
                          height: 48,
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(top: 60.w),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: _canNext
                                  ? ThemeColor.primaryColor
                                  : ThemeColor.primaryColor.withOpacity(0.2)),
                          child: Text(
                            S.current.Done,
                            style: TextStyle(
                              color: _canNext
                                  ? Colors.black
                                  : Colors.black.withOpacity(0.4),
                            ),
                          ),
                        ),
                        onTap: ClickUtils.debounce(
                          () {
                            if (!UtilsComment.checkPasswordFormal(
                                pwsController.text)) {
                              customShowToast(S.of(context).passwordToast_8_16);
                              // return '';
                            } else if (pwsController.text !=
                                againController.text) {
                              customShowToast(S.current.login_pswabove);
                            } else {
                              if (_canNext) {
                                setNewPassword();
                              }
                            }

                            // RouteManager.push(
                            //   context,
                            //   RoutMapping.forgetSetPasswordPage(),
                            // );
                          },
                        ))
                  ],
                ),
              ))),
    );
  }

  setNewPassword() async {
    try {
      if (widget.type == 1) {
        var res = await API.shared.login
            .emailPassword(phone, againController.text, widget.code);
        if (res) {
          customShowSuccess(S.current.changed_successfully);
          Navigator.of(context).pop();
          Navigator.of(context).pop();
        }
      } else {
        var res = await API.shared.login
            .phonePassword(phone, againController.text, widget.code);
        if (res) {
          customShowSuccess(S.current.changed_successfully);
          Navigator.of(context).pop();
          Navigator.of(context).pop();
        }
      }
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowError(e.message);
      // } else {
      //   customShowError(S().network_error);
      // }
    }
  }

  @override
  void initState() {
    super.initState();
    phone = appContext.storage.getString("login_account") ?? '';
    // if (widget.type == 1) {
    //   areaCode = '';

    //   phone = appContext.storage.getString("login_email") ?? '';
    // } else {
    //   String cachePhone = appContext.storage.getString("login_phone") ?? '';
    //   String cachePhoneArea = appContext.storage.getString('login_area') ?? '';
    //   if (cachePhone != '') {
    //     Map<String, dynamic> map = convert.json.decode(cachePhone);
    //     phone = map['phone'];
    //     if (cachePhoneArea != '') {
    //       areaCode = cachePhoneArea;
    //     } else {
    //       areaCode = map['areaCode'];
    //     }
    //   }
    // }
  }

  @override
  void dispose() {
    super.dispose();
    againController.dispose();
    pwsController.dispose();
    pwsFocusNode.dispose();
    againFocusNode.dispose();
  }

  @override
  void didUpdateWidget(ForgetSetPswPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
